<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%; overflow: auto; padding-bottom: 53px"
  >
    <template slot="title">
      <div style="width: 100%">
        <span>{{ title }}</span>
        <span
          style="
            display: inline-block;
            width: calc(100% - 51px);
            padding-right: 10px;
            text-align: right;
          "
        >
          <a-button
            @click="toggleScreen"
            icon="appstore"
            style="height: 20px; width: 20px; border: 0px"
          ></a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item
          label="任务名称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="请输入任务名称"
            :maxLength="20"
            v-decorator.trim="[
              'name',
              {
                rules: validatorRules.name.rules,
                getValueFromEvent: (event) => {
                  return event.target.value.replace(
                    /[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,
                    ''
                  );
                },
              },
            ]"
            :readOnly="title != '编辑'"
            :disabled="this.title == '详情' ? true : false"
          />
        </a-form-item>

        <a-form-item
          label="摄像机编码"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          v-show="false"
        >
          <a-input
            placeholder="请输入摄像机编码"
            :maxLength="20"
            v-decorator.trim="['cameraId']"
            :disabled="this.title == '详情' ? true : false"
          />
        </a-form-item>
        <!-- <a-form-item
          label="摄像机名称"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            placeholder="请输入摄像机名称"
            :maxLength="20"
            v-decorator.trim="[
              'cameraName',
              {
                getValueFromEvent: (event) => {
                  return event.target.value.replace(
                    /[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,
                    ''
                  );
                },
              },
            ]"
            :readOnly="true"
            :disabled="this.title == '详情' ? true : false"
          />
        </a-form-item> -->

        <a-form-item
          label="任务类型"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-radio-group
            v-decorator.trim="['typeId', validatorRules.typeId]"
            button-style="solid"
            :disabled="this.title == '详情' ? true : false"
          >
            <a-radio-button value="0"> 单次 </a-radio-button>
            <a-radio-button value="4"> 长期 </a-radio-button>
            <!--                      <a-radio-button value="3">-->
            <!--                        月-->
            <!--                      </a-radio-button>-->
            <!--                      <a-radio-button value="2">-->
            <!--                        周-->
            <!--                      </a-radio-button>-->
            <!--                      <a-radio-button value="1">-->
            <!--                        日-->
            <!--                      </a-radio-button>-->
          </a-radio-group>
        </a-form-item>

        <a-form-item
          v-if="form.getFieldValue('typeId') == 0"
          label="开始时间"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-date-picker
            :disabled="this.title == '详情' ? true : false"
            setFieldsValue="startValue"
            :disabled-date="disabledDate"
            show-time
            :allowClear="false"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择开始日期时间"
            @openChange="handleStartOpenChange"
            v-decorator="['rangeValue', validatorRules.rangeValue]"
          />
          <!-- <a-range-picker
            :disabled="this.title == '详情' ? true : false"
            size="small"
            :show-time="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            :placeholder="['开始时间', '结束时间']"
            :disabled-date="disabledDate"
            v-decorator="['rangeValue', validatorRules.rangeValue]"
            @change="onChangeRangeDate"
          /> -->
        </a-form-item>
        <a-form-item
          v-if="form.getFieldValue('typeId') == 0"
          label="结束时间"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-date-picker
            :disabled="this.title == '详情' ? true : false"
            setFieldsValue="endValue"
            :disabled-date="disabledDate"
            show-time
            :allowClear="false"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择结束日期时间"
            @openChange="handleEndOpenChange"
            :open="endOpen"
            v-decorator="[
              'rangeValues',
              {
                rules: validatorRules.rangeValues.rules,
              },
            ]"
          />

          <!-- 结束时间  不选择 
             {
                rules: this.endTimeValue
                  ? validatorRules.rangeValues.rules
                  : rules,
              } -->
        </a-form-item>

        <!-- 更新时间  创建时间 -->
        <a-form-item
          label="更新时间"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            v-decorator="['updateTime']"
            :readOnly="true"
            :disabled="true"
          />
        </a-form-item>
        <a-form-item
          label="创建时间"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
        >
          <a-input
            v-decorator="['createTime']"
            :readOnly="true"
            :disabled="true"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="任务描述"
        >
          <a-textarea
            placeholder="任务描述"
            v-decorator.trim="[
              'taskDesc',
              {
                getValueFromEvent: (event) => {
                  return event.target.value.replace(
                    /[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,
                    ''
                  );
                },
              },
            ]"
            :disabled="this.title == '详情' ? true : false"
            :maxLength="40"
          />
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="启用状态"
          name="启用状态"
        >
          <a-switch
            v-decorator.trim="[
              'used',
              {
                rules: [{ required: true, message: '请输入选择' }],
                valuePropName: 'checked',
              },
            ]"
            :disabled="this.title == '详情' ? true : false"
          />
        </a-form-item>
      </a-form>
    </a-spin>

    <div class="drawer-bootom-button">
      <a-button
        @click="handleEdit"
        type="primary"
        :loading="confirmLoading"
        v-if="!disabledEditValue && disabledAddValue"
        >编辑</a-button
      >
      <a-button
        @click="handleSubmit"
        type="primary"
        :loading="confirmLoading"
        v-if="disabledEditValue && !disabledAddValue"
        >提交</a-button
      >
      <a-popconfirm
        title="确定放弃编辑？"
        @confirm="handleCancel"
        okText="确定"
        cancelText="取消"
        v-if="disabledEditValue"
      >
        <a-button style="margin-left: 0.8rem">取消</a-button>
      </a-popconfirm>
      <a-button
        style="margin-left: 0.8rem"
        v-if="!disabledEditValue"
        @click="handleCancel"
        >取消</a-button
      >
    </div>

    <!-- <div class="drawer-bootom-button" v-show="disableSubmit"></div> -->
  </a-drawer>
</template>

<script>
import pick from "lodash.pick";
import { getAction } from "@/api/manage";
import moment from "moment";
import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import { modifyRecordTask } from "@/api/api";
import { disabledAuthFilter } from "@/utils/authFilter";
import JImageUpload from "../../../components/jeecg/JImageUpload";

export default {
  name: "UserModal",
  mixins: [JeecgListMixin],
  components: {
    JImageUpload,
  },
  data() {
    return {
      endOpen: false,
      departDisabled: false, //是否是我的部门调用该页面
      roleDisabled: false, //是否是角色维护调用该页面
      modalWidth: 800,
      drawerWidth: 700,
      modaltoggleFlag: true,
      confirmDirty: false,
      taskId: "", //保存任务id
      disableSubmit: false,
      validatorRules: {
        name: {
          rules: [
            {
              required: true,
              message: "请输入任务名称!",
            },
          ],
        },
        rangeValue: {
          rules: [
            {
              required: true,
              message: "请选择录像时间段!",
            },
          ],
        },
        rangeValues: {
          rules: [
            {
              required: true,
              message: "请选择录像时间段!",
            },
          ],
        },

        typeId: {
          rules: [
            {
              required: true,
              message: "请选择任务类型!",
            },
          ],
        },
      },
      title: "操作",
      visible: false,
      model: {},
      roleList: [],
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 5,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
      uploadLoading: false,
      confirmLoading: false,
      form: this.$form.createForm(this),
      currentTenant: [],
      treeData: [],
    };
  },
  created() {
    this.form.getFieldDecorator("rangeValue", {
      initialValue: "",
      preserve: true,
    });
    this.form.getFieldDecorator("rangeValues", {
      initialValue: "",
      preserve: true,
    });
  },
  computed: {},
  methods: {
    // 编辑
    handleEdit() {
      this.title = "编辑";
      this.disabledEditValue = true;
      this.disabledAddValue = false;
    },
    onChangeRangeDate(value, dateString) {
      console.log("---------日期发生变化，可以修改---------");
      console.log(dateString);

      if (dateString[0] === dateString[1]) {
        console.log("----------时间相同了-------------");
        this.$message.warning("开始时间与结束时间相同");
      }
    },

    handleStartOpenChange(open) {
      if (!open) {
        this.endOpen = true;
      }
    },
    handleEndOpenChange(open) {
      this.endOpen = open;
    },
    isDisabledAuth(code) {
      return disabledAuthFilter(code);
    },
    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth;
      } else {
        this.modalWidth = 800;
      }
      this.modaltoggleFlag = !this.modaltoggleFlag;
    },
    refresh() {
      this.taskId = "";
      this.departId = [];
      this.currentTenant = [];
    },
    add() {},
    edit(record) {
      console.log(record);
      let that = this;
      if (record.taskId) {
        getAction("/record/info/" + record.taskId).then((res) => {
          if (res.code == "00000") {
            this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
            that.form.resetFields();
            that.taskId = res.data.taskId;
            that.visible = true;
            that.endTimeValue = res.data.endDateTime;
            console.log(res.data, "-------res.data的数据-------");
            that.model = Object.assign({}, res.data);
            // that.model.rangeValue = [];
            // that.model.rangeValues = [];

            // that.model.rangeValue.push(
            //   moment(res.data.startDateTime, "YYYY-MM-DD HH:mm:ss")
            // );

            // if (res.data.endDateTime) {
            //   that.model.rangeValue.push(
            //     moment(res.data.startDateTime, "YYYY-MM-DD HH:mm:ss")
            //   );
            //   that.model.rangeValues.push(
            //     moment(res.data.endDateTime, "YYYY-MM-DD HH:mm:ss")
            //   );
            // } else {
            //   that.model.rangeValue.push(
            //     moment(res.data.startDateTime, "YYYY-MM-DD HH:mm:ss")
            //   );
            // }

            console.log(res.data.endDateTime, res.data.startDateTime);
            console.log("开始时间与结束时间展示");

            if (res.data.endDateTime) {
              that.model.rangeValues = res.data.endDateTime;
              that.model.rangeValue = res.data.startDateTime;
            } else {
              that.model.rangeValue = res.data.startDateTime;
            }

            // console.log("that.model.rangeValue", that.model.rangeValue);
            // console.log("that.model.rangeValues", that.model.rangeValueas);

            that.$nextTick(() => {
              that.form.setFieldsValue({
                used: that.model.used == "1" ? true : false,
              });
              that.form.setFieldsValue(
                pick(
                  that.model,
                  "name",
                  "typeId",
                  "rangeValue",
                  "rangeValues",
                  "taskDesc",
                  "cameraId",
                  "cameraName",
                  "updateTime",
                  "createTime"
                )
              );
            });
          } else {
            that.$message.warning("查询失败");
          }
        });
      } else {
        this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        this.form.resetFields();
        this.userId = record.userId;
        this.visible = true;
        this.model = Object.assign({}, record);
        this.$nextTick(() => {
          that.form.setFieldsValue(
            pick(
              that.model,
              "name",
              "typeId",
              "rangeValue",
              "rangeValues",
              "taskDesc",
              "cameraId",
              "cameraName",
              "updateTime",
              "createTime"
            )
          );
        });
      }
    },

    close() {
      this.$emit("close");
      this.visible = false;
      this.disableSubmit = false;
    },
    // moment,
    handleSubmit() {
      const that = this;
      // 触发表单验证
      console.log("提交编辑数据");
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let formData = Object.assign(this.model, values);

          // 判断任务类型
          if (formData.typeId == "0") {
            formData.startDateTime = moment(values["rangeValue"]).format(
              "YYYY-MM-DD HH:mm:ss"
            );
            formData.endDateTime = moment(values["rangeValues"]).format(
              "YYYY-MM-DD HH:mm:ss"
            );

            console.log(
              formData.startDateTime,
              formData.endDateTime,
              "开始时间与结束时间"
            );

            // 提交时间判断
            let start = formData.startDateTime.replace(/-/g, "");
            let starts = start.replace(/:/g, "");
            let startes = starts.replace(/ /g, "");
            console.log(startes);
            let end = formData.endDateTime.replace(/-/g, "");
            let ends = end.replace(/:/g, "");
            let endes = ends.replace(/ /g, "");
            console.log(endes);

            if (startes == endes) {
              that.$message.warning("操作失败开始时间与结束时间相同");
              that.confirmLoading = false;
              that.close();
              return;
            }
            if (startes > endes) {
              that.$message.warning("操作失败开始时间应早于结束时间");
              that.confirmLoading = false;
              that.close();
              return;
            }
          } else if (formData.typeId == "4") {
            formData.startDateTime = null;
            formData.endDateTime = null;
          }

          formData.used = values["used"] ? "1" : "0";
          console.log(formData);

          let obj = modifyRecordTask(formData);
          obj
            .then((res) => {
              if (res.code == "00000") {
                that.$message.success("操作成功");
                that.$emit("ok");
              } else {
                that.$message.warning("操作失败" + res.msg);
              }
            })
            .finally(() => {
              that.confirmLoading = false;
              that.close();
            });
        }
      });
    },
    handleCancel() {
      this.close();
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form;
      const confirmpassword = form.getFieldValue("confirmpassword");

      if (value && confirmpassword && value !== confirmpassword) {
        callback("两次输入的密码不一样！");
      }
      if (value && this.confirmDirty) {
        form.validateFields(["confirm"], {
          force: true,
        });
      }
      callback();
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form;
      if (value && value !== form.getFieldValue("password")) {
        callback("两次输入的密码不一样！");
      } else {
        callback();
      }
    },
    validatePhone(rule, value, callback) {
      if (!value) {
        callback("请输入手机号码!");
      } else {
        //update-begin--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
        if (new RegExp(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/).test(value)) {
          //update-end--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
          callback();
        } else {
          callback("请输入正确格式的手机号码!");
        }
      }
    },
    validateEmail(rule, value, callback) {
      if (!value) {
        callback();
      } else {
        if (
          new RegExp(
            /^(([^<>()\]\\.,;:\s@"]+(\.[^<>()\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
          ).test(value)
        ) {
          callback();
        } else {
          callback("请输入正确格式的邮箱!");
        }
      }
    },
    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },
    // handleChange(info) {
    // 	this.picUrl = "";
    // 	if (info.file.status === 'uploading') {
    // 		this.uploadLoading = true;
    // 		return
    // 	}
    // 	if (info.file.status === 'done') {
    // 		var response = info.file.response;
    // 		this.uploadLoading = false;
    // 		console.log(response);
    // 		if (response.success) {
    // 			this.model.avatar = response.message;
    // 			this.picUrl = "Has no pic url yet";
    // 		} else {
    // 			this.$message.warning(response.message);
    // 		}
    // 	}
    // },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth;
      } else {
        this.drawerWidth = 700;
      }
    },
    disabledDate(current) {
      // 限制只能选今天及之后的日期（今天可选中）
      return current && current < moment().subtract(1, "days").endOf("day");
    },
  },
};
</script>

<style scoped>
.avatar-uploader > .ant-upload {
  width: 104px;
  height: 104px;
}

.ant-upload-select-picture-card i {
  font-size: 49px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}

.drawer-bootom-button {
  position: absolute;
  bottom: -8px;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
</style>
